// 创建一个路由器，并暴露出去
// 第一步：引入createRouter
import {createRouter, createWebHistory} from 'vue-router'
// 引入一个一个可能要呈现组件
import Login from '@/views/Login.vue'
import Index from '@/views/admin/Index.vue'
import Admin from '@/views/admin/Admin.vue'
import Course from '@/views/admin/Course.vue'
import Coach from "@/views/admin/Coach.vue"
import Chart from "@/views/admin/Chart.vue"
import Role from "@/views/admin/Role.vue"
import Permission from "@/views/admin/Permission.vue"
import UserIndex from "@/views/user/UserIndex.vue"
import UserChart from "@/views/user/UserChart.vue"
import UserReserve from "@/views/user/UserReserve.vue"

//创建路由器
const router = createRouter({
    history: createWebHistory(),
    routes: [
        {path: '/login', component: Login},
        {
            path: '/admin', component: Index, children: [
                {path: '/admin/admin', component: Admin},
                {path: '/admin/course', component: Course},
                {path: '/admin/coach', component: Coach},
                {path: '/admin/chart', component: Chart},
                {path: '/admin/role', component: Role},
                {path: '/admin/permission', component: Permission}
            ]
        },
        {
            path: '/user', component: UserIndex, children: [
                {path: '/user/reserve', component: UserReserve},
                {path: '/user/chart', component: UserChart},
            ]
        }
    ]
})

//https://v3.router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E5%AE%88%E5%8D%AB
//路由守卫
//全局前置守卫
import {useTokenStore} from '@/store/token.js'
import {ElMessage} from "element-plus";
let whiteList = ['/login']; // 白名单
router.beforeEach((to, from, next) => {
    const tokenStore = useTokenStore()
    const token = tokenStore.token;
    if (!whiteList.includes(to.path) && !token) {
        next('/login')
    } else {
        console.log(to.path)
        const type = localStorage.getItem('type');
        if (type == 1 && to.path == '/') {
            next('/admin')
            return;
        } else if (type == 2 && to.path == '/') {
            next('/user')
            return;
        }

        if (type == 1 && !to.path.startsWith('/admin') && to.path != '/login') {
            ElMessage.error('没有访问权限')
            return
        } else if (type == 2 && !to.path.startsWith('/user') && to.path != '/login') {
            ElMessage.error('没有访问权限')
            return
        }


        next()
    }
})

// 暴露出去router
export default router